import { getSearchImage } from '../../api/index'

Page({
  data: {
    fileId: '',
    fileUrl: '',
    queryUrl: '',
    activeCate: '',
    pageSize: 20,
    currentPage: 1,
    isEmpty: false,
    cateList: [],
    materialList: [],
    show: false,
    popHeight: 200,
    isSpread: false,
    overflow: 'auto'
  },
  change ({ detail }) {
    this.setData({
      queryUrl: detail[0].fileUrl,
      overflow: 'auto' 
    })
    this.getSearchImage()
  },
  changeOverflow () {
    this.setData({ overflow: 'hidden' })
  },
  selectCate ({ currentTarget: { dataset: { item } } }) {
    if (item) {
      this.setData({ activeCate: item.classificationId })
    } else {
      this.setData({ activeCate: '' })
    }
    this.getSearchImage()
  },
  toggleHeight () {
    const { windowHeight } = wx.getSystemInfoSync()
    if (this.data.isSpread) {
      this.setData({ popHeight: 200, isSpread: false })
    } else {
      this.setData({ popHeight: windowHeight - 50, isSpread: true })
    }
  },
  async getSearchImage () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      let query = {
        fileUrl: this.data.queryUrl,
      }
      if (this.data.activeCate) query.classificationId = this.data.activeCate
      const { ResultSet } = await getSearchImage({ ...query })
      this.data.isEmpty = ResultSet.userData.simDatas.length && ResultSet.userData.simDatas.length < this.data.pageSize
      this.setData({
        show: true,
        isEmpty: this.data.isEmpty,
        cateList: ResultSet.userData.classifications,
        materialList: ResultSet.userData.simDatas
      })
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ fileId, fileUrl }) {
    this.setData({
      fileId: fileId,
      queryUrl: decodeURIComponent(fileUrl),
      fileUrl: decodeURIComponent(fileUrl)
    })
    // this.getSearchImage()
  }
})